﻿

using CoreCms.Net.Auth.HttpContextUser;
using CoreCms.Net.Configuration;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.DTO;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Repository;
using CoreCms.Net.Services;
using CoreCms.Net.Utility.Helper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetTaste;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Nito.AsyncEx;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace CoreCms.Net.Web.WebApi.Controllers
{
    /// <summary>
    /// 经纪人控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BrokerController : ControllerBase
    {
        private IHttpContextUser _user;
        private IXrcApplyBrokerServices _xrcApplyBrokerService;
        private readonly AsyncLock _mutex = new AsyncLock();
        private ICoreCmsUserWeChatInfoServices _userWeChatInfoServices;
        private IXrcOrderServices _xrcOrderServices;
        private readonly ICoreCmsMessageCenterServices _messageCenterServices;
        private readonly IXrcCommissinService _xrcCommissinService;
        private readonly IUnitOfWork _unitOfWork;
        private IXrcAdminServices _xrcAdminServices;

        private IXrcBrokerExitServices _xrcBrokerExitServices;


        private readonly IXrcCommissinRepository _xrcCommissinRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="user"></param>
        /// <param name="xrcApplyBrokerService"></param>
        public BrokerController(IHttpContextUser user, IXrcApplyBrokerServices xrcApplyBrokerService, ICoreCmsUserWeChatInfoServices userWeChatInfoServices, IXrcOrderServices xrcOrderServices, ICoreCmsMessageCenterServices messageCenterServices, IXrcCommissinService xrcCommissinService
              , IXrcCommissinRepository xrcCommissinRepository, IUnitOfWork unitOfWork, IXrcAdminServices xrcAdminServices, IXrcBrokerExitServices xrcBrokerExitServices)
        {
            _user = user;
            _xrcApplyBrokerService = xrcApplyBrokerService;
            _userWeChatInfoServices = userWeChatInfoServices;
            _xrcOrderServices = xrcOrderServices;
            _messageCenterServices = messageCenterServices;
            _xrcCommissinService = xrcCommissinService;
            _xrcCommissinRepository = xrcCommissinRepository;
            _xrcBrokerExitServices = xrcBrokerExitServices;
            _unitOfWork = unitOfWork;
            _xrcAdminServices = xrcAdminServices;
        }


        #region 经纪人 我的团队列表
        /// <summary>
        /// 经纪人 我的团队列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> MyBrokerList([FromBody] FMPageByIntId entity)
        {
            var jm = new WebApiCallBack();
            var type = OrderByType.Desc;
            if (entity.order == "Asc")
                type = OrderByType.Asc;

            var list = _xrcApplyBrokerService.QueryListAsync(_user.ID, entity.where, type);
            for (int i = 0; i < list.Count; i++)
            {
                list[i].StateMsg = GetStateMsg(list[i].State);
            }
            jm.otherData = list.Count;
            jm.status = true;
            jm.data = list;
            return jm;
        }

        #endregion

        #region 经纪人推广订单列表
        /// <summary>
        /// 经纪人推广订单列表  brokertype=1 当前经纪人 我的客户订单   brokertype=2  当前经纪人下级人员客户订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> OrderList([FromBody] FMOrderList entity)
        {
            var jm = new WebApiCallBack();
            Expression<Func<XrcOrder, bool>> where = m => m.Delete == false;
            if (entity.state > 0)
            {
                where = where.And(p => p.State == entity.state);
            }
            if (entity.isloin > 0)
            {
                where = where.And(p => p.IsLoin == entity.isloin);
            }
            if (entity.brokertype > 0)
            {
                if (entity.brokertype == 1)
                {
                    where = where.And(p => p.BrokerId == _user.ID);
                }
                else if (entity.brokertype == 2)
                {
                    var items = await _xrcApplyBrokerService.QueryListByClauseAsync(p => p.ParentId == _user.ID);
                    var idsInts = items.Select(p => p.Userid).ToArray();
                    where = where.And(p => idsInts.Contains(p.BrokerId));
                }
            }
            var list = await _xrcOrderServices.QueryPageAsync(where, p => p.AddTime, OrderByType.Desc,
                entity.page, entity.limit);

            List<OrderListDto> dtolist = list.Select(p => new OrderListDto
            {
                Id = p.Id,
                Gid = p.Gid,
                UserId = p.UserId,
                ProId = p.ProId,
                BrokerId = p.BrokerId,
                BrokerName = "",
                BrokerMobile = "",
                ProName = p.ProName,
                ProType = p.ProType,
                RealityQuota = p.RealityQuota,
                Commission = p.Commission,
                Name = p.Name,
                Mobile = p.Mobile,
                ExpQuota = p.ExpQuota,
                State = p.State,
                StateMsg = "",
                IsLoin = p.IsLoin,
                IsLoinMsg = "",
                AddTime = p.AddTime,
                Upter = p.Upter,
                UpTime = p.UpTime,
                Delete = p.Delete,
                Remark = p.Remark
            }).ToList();

            for (int i = 0; i < dtolist.Count; i++)
            {
                if (list[i].BrokerId > 0)
                {
                    var tuijianren = _xrcApplyBrokerService.QueryByClause(p => p.Userid == list[i].BrokerId);
                    dtolist[i].BrokerName = tuijianren.Name;
                    dtolist[i].BrokerMobile = tuijianren.Mobile;
                }
                dtolist[i].StateMsg = dtolist[i].State == 0 ? "审核中" : dtolist[i].State == 1 ? "审核成功" : "审核失败";
                dtolist[i].IsLoinMsg = dtolist[i].IsLoin == 0 ? "审核中" : dtolist[i].IsLoin == 1 ? "已放款" : "未放款";

            }
            jm.otherData = list.TotalCount;
            jm.status = true;
            jm.data = dtolist;
            return jm;
        }

        #endregion

        private string GetStateMsg(int state)
        {
            switch (state)
            {
                case 0: return "待审核";
                case 1: return "审核成功";
                case 2: return "审核未通过";
                default: return "未知";

            }

        }

        #region  一级经纪人修改二级经纪人比例=========================================================
        /// <summary>
        /// 一级经纪人修改二级经纪人比例
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> UpdataScale([FromBody] FMBrokerSare entity)
        {
            var jm = new WebApiCallBack();

            if (entity.id > 0)
            {

                if (entity.scale > 0)
                {
                    var model = await _xrcApplyBrokerService.QueryByClauseAsync(p => p.Userid == _user.ID);
                    if (model != null)
                    {
                        if (entity.scale > model.scale)
                        {
                            jm.code = -1;
                            jm.msg = "修改下级佣金比例不能大于上级佣金比例";
                            return jm;
                        }
                    }
// var nowmodel   = _xrcApplyBrokerService.QueryByIdAsync(entity.id);
; bool ret = await _xrcApplyBrokerService.UpdateAsync(p => new XrcApplyBroker() { scale = entity.scale },
                                 p => p.Id == entity.id);
                    if (ret)
                    {
                        jm.status = true;
                        jm.msg = "修改成功";
                    }
                    else
                    {
                        jm.code = -1;
                        jm.msg = "修改失败";
                    }
                }
                else
                {
                    jm.code = -1;
                    jm.msg = "佣金比例不能小于0";
                }
            }

            return jm;
        }

        #endregion

        #region  解除成员=========================================================
        /// <summary>
        /// 解除成员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> Unbind([FromBody] FMBrokerSare entity)
        {
            var jm = new WebApiCallBack();

            if (entity.id > 0)
            {
                bool ret = await _xrcApplyBrokerService.UpdateAsync(p => new XrcApplyBroker() { ParentId = 0 }, p => p.Id == entity.id);
                if (ret)
                {
                    jm.status = true;
                    jm.msg = "解绑成功";
                }
                else
                {
                    jm.status = true;
                    jm.msg = "解绑失败";
                }
            }

            return jm;
        }

        #endregion

        #region  申请为经纪人=========================================================

        /// <summary>
        /// 申请为经纪人
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> CreateBroker([FromBody] FMApplyBroker entity)
        {
            var jm = new WebApiCallBack { methodDescription = "", data = null };
            if (!string.IsNullOrEmpty(entity.Name))
            {
                int? borkeruserid = 0;
                var brokerUser = await _xrcApplyBrokerService.QueryByIdAsync(entity.ParentId);
                if (brokerUser != null)
                    borkeruserid = brokerUser.Userid;
                if (brokerUser != null && brokerUser.Userid == _user.ID)
                {
                    jm.msg = "自己不能邀请自己";
                    jm.status = false;
                    return jm;
                }
                if (brokerUser != null && brokerUser.ParentId > 0)
                {
                    jm.msg = "当前上级经纪人,已在其他经纪人团队不能再次绑定,请换其他经纪人";
                    jm.status = false;
                    return jm;
                }

                //-----------------jd start 2023/08/22---------------
                using (await _mutex.LockAsync())
                {
                    var applyBroker = await _xrcApplyBrokerService.QueryByClauseAsync(p => p.Userid == _user.ID && p.Delete == 0);

                    int add = 0;
                    bool ret = false;
                    if (applyBroker == null)
                    {
                        //没有数据，创建新数据
                        applyBroker = new XrcApplyBroker
                        {
                            CreateTime = DateTime.Now,
                            Delete = 0,
                            Fall = "",
                            Gid = entity.Store,
                            Id = 0,
                            scale = 0,
                            Mobile = entity.Mobile,
                            Name = entity.Name,
                            Openid = entity.OpenId,
                            ParentId = borkeruserid,
                            state = 0,
                            UpdateTime = DateTime.Now,
                            Userid = _user.ID
                        };
                        add = await _xrcApplyBrokerService.InsertAsync(applyBroker);

                        jm.msg = add > 0 ? "申请成功，审核中" : "网络请求超时，请联系管理员";
                        jm.status = add > 0 ? true : false;
                    }
                    else
                    {
                        //数据已存在
                        switch (applyBroker.state)
                        {
                            case 0:
                                jm.msg = "当前申请正在审核中，请勿重复申请";
                                jm.status = false;
                                break;
                            case 1:
                                jm.msg = "当前申请已通过，无需重复申请";
                                jm.status = false;
                                break;
                            case 2:
                                applyBroker.state = 0;
                                ret = await _xrcApplyBrokerService.UpdateAsync(applyBroker);
                                jm.msg = "已重新提交申请经纪人，请等待审核";
                                jm.status = true;
                                break;
                        }
                    }

                    if (add > 0 || ret)
                    {
                        var admins = await _xrcAdminServices.QueryListByClauseAsync(p => p.state == 1 && p.gid == entity.Store);
                        if (admins.Count > 0)
                        {
                            var userids = admins.Select(p => p.userid).ToArray();
                            if (userids.Length > 0)
                            {
                                for (int i = 0; i < userids.Length; i++)
                                {
                                    if (userids[i] > 0)
                                    {
                                        await _messageCenterServices.SendMessage(userids[i], GlobalEnumVars.PlatformMessageTypes.ApplyBroker.ToString(), JObject.FromObject(applyBroker));
                                    }
                                }
                            }
                        }
                    }
                }
                //-----------------jd end-----------------------------
            }
            else
            {
                jm.msg = "缺少参数";
                jm.status = false;
            }
            return jm;
        }
        #endregion



        #region  是否为经纪人=========================================================
        /// <summary>
        /// 是否是一级经纪人
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public WebApiCallBack IsBroker()
        {
            var jm = new WebApiCallBack();
            if (_xrcApplyBrokerService.QueryByClauseAsync(p => p.Userid == _user.ID && p.Delete == 0 && p.state == 1 && p.ParentId == 0).Result != null)
            {
                jm.data = 1;
                jm.status = true;
                jm.msg = "一级经纪人";
            }
            else if (_xrcApplyBrokerService.QueryByClauseAsync(p => p.Userid == _user.ID && p.Delete == 0 && p.state == 1 && p.ParentId > 0).Result != null)
            {

                jm.data = 2;
                jm.status = true;
                jm.msg = "二级经纪人";
            }
            else
            {
                jm.data = 0;
                jm.status = true;
                jm.msg = "不是经纪人";
            }
            return jm;
        }

        #endregion


        #region  是否通过=========================================================
        /// <summary>
        /// 是否通过
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<WebApiCallBack> IsPassed()
        {
            var jm = new WebApiCallBack();
            var model = await _xrcApplyBrokerService.QueryListByClauseAsync(p => p.Userid == _user.ID && p.Delete == 0, "id");
            if (model.Count <= 0)
            {
                jm.data = -1;
                jm.status = true;
                jm.msg = "未申请经纪人";
            }
            else
            {
                if (model[0].state == 0)
                {
                    jm.data = 0;
                    jm.status = true;
                    jm.msg = "审核中";
                }
                else if (model[0].state == 1)
                {
                    jm.data = 1;
                    jm.status = true;
                    jm.msg = "审核通过";
                }
                else if (model[0].state == 2)
                {
                    jm.data = 2;
                    jm.status = true;
                    jm.msg = "审核失败";
                }
            }
            return jm;
        }

        #endregion

        #region 获取经纪人解密Id

        /// <summary>
        /// 获取经纪人解密Id
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiCallBack GetShareCode([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();

            if (entity.id > 0)
            {
                entity.id = UserHelper.GetUserIdByShareCode(entity.id);
                jm.status = true;
                jm.data = entity.id;
            }
            return jm;

        }

        #endregion

        #region 经纪人详情
        /// <summary>
        /// 获取经纪人详情
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetBrokerDetail([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();
            var model = await _xrcApplyBrokerService.QueryByClauseAsync(p => p.Userid == entity.id && p.Delete == 0);
            if (model == null)
            {
                jm.status = true;
                jm.msg = "未查询到经纪人";
                return jm;
            }
            jm.status = true;
            jm.data = model;
            return jm;

        }
        #endregion

        #region 分佣明细
        /// <summary>
        /// 分佣明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> CommissinList([FromBody] FMPageByIntId entity)
        {
            var jm = new WebApiCallBack();
            Expression<Func<XrcCommission, bool>> where = m => m.Delete == 0;
            var list = await _xrcCommissinService.QueryMuchAsync<XrcCommission, XrcOrder, CommissinDto>((x, o) => new object[] {
              JoinType.Left ,x.Order_Id ==o.Id
            }, (x, o) => new CommissinDto
            {
                Id = x.Id,
                Order_Id = x.Order_Id,
                Rate = x.Rate,
                User_Id = x.User_Id,
                UserName = o.Name,
                ProName = o.ProName,
                ProcessTime = o.ProcessTime,
                Price = x.Price,
                CreateTime = x.CreateTime,
                Delete = x.Delete,
                State = x.State,
                Remark = x.Remark
            }, (x, o) => x.State == 0 && x.Delete == 0 && x.User_Id == _user.ID);

            jm.status = true;
            jm.data = new
            {
                list,
                count = list.Count,
                AllPrice = list.Sum(x => x.Price),
            };
            return jm;
        }

        #endregion

        #region 申请退出经纪人团队
        /// <summary>
        /// 申请退出经纪人团队
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> ExitTeam()
        {
            var jm = new WebApiCallBack();

            var brokerUser = await _xrcApplyBrokerService.QueryByClauseAsync(P => P.Userid == _user.ID);
            if (brokerUser != null && brokerUser.Id > 0)
            {

                using (await _mutex.LockAsync())
                {
                    int add = 0;
                    bool ret = false;
                    var applyBroker = await _xrcBrokerExitServices.QueryByClauseAsync(p => p.UserId == _user.ID);
                    if (applyBroker == null)
                    {
                        //没有数据，创建新数据
                        applyBroker = new XrcBrokerExit
                        {
                            CreateTime = DateTime.Now,
                            Name = brokerUser.Name,
                            ParentId = Convert.ToInt32(brokerUser.ParentId),
                            state = 0,
                            UserId = _user.ID,

                        };
                        add = await _xrcBrokerExitServices.InsertAsync(applyBroker);

                        jm.msg = add > 0 ? "申请成功" : "网络请求超时，请联系管理员";
                        jm.status = add > 0 ? true : false;
                    }
                    else
                    {
                        //数据已存在
                        switch (applyBroker.state)
                        {
                            case 0:
                                jm.msg = "当前申请正在审核中，请勿重复申请";
                                jm.status = false;
                                break;
                            case 1:
                                jm.msg = "当前申请已通过，无需重复申请";
                                jm.status = false;
                                break;
                            case 2:
                                applyBroker.state = 0;
                                ret = await _xrcBrokerExitServices.UpdateAsync(applyBroker);
                                jm.msg = "已申请退出团队，请等待上级经纪人审核通过";
                                jm.status = true;
                                break;
                        }
                    }
                    if (add > 0 || ret)
                    {
                        if (applyBroker.ParentId > 0)
                        {
                            await _messageCenterServices.SendMessage(applyBroker.ParentId, GlobalEnumVars.PlatformMessageTypes.BrokerExit.ToString(), JObject.FromObject(applyBroker));
                        }
                    }
                }
            }
            else
            {
                jm.msg = "未查询到经纪人信息";
                jm.status = false;
            }
            return jm;
        }
        #endregion

        #region 获取退团申请列表 
        /// <summary>
        /// 获取退团申请列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> BrokerExitList([FromBody] FMPageByWhereOrder entity)
        {
            var jm = new WebApiCallBack();
            var where = PredicateBuilder.True<XrcBrokerExit>();
            where = where.And(p => p.ParentId == _user.ID);
            where = where.And(p => p.state == entity.status);
            var list = await _xrcBrokerExitServices.QueryPageAsync(where, "create_time", entity.page, entity.limit);
            jm.otherData = list.Count;
            jm.status = true;
            jm.data = list;
            return jm;
        }
        #endregion

        #region  审核退队成员=========================================================
        /// <summary>
        /// 审核退队成员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> ExamineExit([FromBody] FMBrokerExit entity)
        {
            var jm = new WebApiCallBack();
            if (entity.id > 0 && entity.state > 0)
            {
                XrcBrokerExit xrcBrokerExit = _xrcBrokerExitServices.QueryById(entity.id);
                if (xrcBrokerExit != null && xrcBrokerExit.Id > 0)
                {
                    xrcBrokerExit.UpdateTime = DateTime.Now;
                    xrcBrokerExit.state = entity.state;

                    bool ret = _xrcBrokerExitServices.Update(xrcBrokerExit);
                    if (ret)
                    {
                        //审核通过  把成员更新成一级经纪人
                        if (xrcBrokerExit.state == 1)
                        {
                            await _xrcApplyBrokerService.UpdateAsync(p => new XrcApplyBroker() { ParentId = 0 }, p => p.Userid == xrcBrokerExit.UserId);
                        }
                        //给用户发送模板消息
                        await _messageCenterServices.SendMessage(xrcBrokerExit.UserId, GlobalEnumVars.PlatformMessageTypes.BrokerExit.ToString(), JObject.FromObject(xrcBrokerExit));
                        jm.status = true;
                        jm.msg = "审核成功";
                    }
                    else
                    {
                        jm.status = true;
                        jm.msg = "审核失败";
                    }
                }
                else
                {
                    jm.status = false;
                    jm.msg = "未查询到申请记录";
                }
            }
            else
            {
                jm.status = false;
                jm.msg = "审核异常,参数错误。";
            }
            return jm;
        }
        #endregion
    }
}
